package com.chaucer.demo.transmit;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 转发业务来源
 */
public class ForwardRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        String businessSource = BusinessSourceThreadLocal.get();
        if (businessSource != null) {
            template.header(IsolateConstants.businessSourceKey, businessSource);
        }

        //转发FilterUserName、appCode
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String filterUserName = request.getHeader(IsolateConstants.FILTER_USER_NAME);
            if (StringUtils.isNotEmpty(filterUserName)) {
                template.header(IsolateConstants.FILTER_USER_NAME, filterUserName);
            }

            String appCode = request.getHeader(IsolateConstants.APP_CODE_HEADER);
            if (StringUtils.isNotEmpty(appCode)) {
                template.header(IsolateConstants.APP_CODE_HEADER, appCode);
            }
        }

    }
}
